//
//  FMDBDataBaseManager.m
//  MyProject
//
//  Created by apple on 15/11/7.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "FMDBDataBaseManager.h"

static FMDBDataBaseManager *manager = nil;

@implementation FMDBDataBaseManager

+(FMDBDataBaseManager *)shareMagager
{
    @synchronized (self){
        if (!manager) {
            manager = [[self alloc]init];
        } 
    }
    return manager;
}

-(instancetype)init
{
    self = [super init];
    if (self) {
        
        NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/LvYou.db"];
        
        _dataBase = [[FMDatabase alloc]initWithPath:path];
        if (!_dataBase) {
            NSLog(@"创建数据库失败");
            return nil;
        }
        [self openDatabase];
        
        //创建表
        [self createTable];
        
        
    }
    return self;
}


-(void)openDatabase
{
    BOOL result = [_dataBase open];
    if (!result) {
        NSLog(@"打开数据库失败");
        [_dataBase close];
    }
}

-(void)createTable
{
    //NSString * sql = @"create table if not exists LvYou(id integer primary key autoincrement, image_id varchar[1000], image_url varchar[1024], name_en varchar[1024]);";
    NSString * sql = @"create table if not exists LvYou(id integer primary key autoincrement, image_id varchar[1000], image_url varchar[1024], name varchar[1024] ,nameen varchar[1024]);";
    
    BOOL result = [_dataBase executeUpdate:sql];
    if (!result) {
        NSLog(@"创建表失败");
        [_dataBase close];
    }
    
}

//插入
- (void)insertDataWithModel:(KouDaiDetailModel *)model
{

    NSString * sql = @"insert into LvYou(image_id, image_url, name, nameen) values (?, ?, ?, ?);";
    
    
    BOOL result = [_dataBase executeUpdate:sql,model.id,model.image_url,model.name_zh_cn,model.name_en];
    if (!result) {
        NSLog(@"插入数据失败");
        //[_dataBase close];
    }
}

//删除

-(void)deleteDataWithModel:(KouDaiDetailModel *)model
{
    NSString *sql = @"delete from LvYou where image_id = ?;";
    
    BOOL result = [_dataBase executeUpdate:sql,model.id];
    if (!result) {
        NSLog(@"删除数据失败");
    }
    
}

//查找数据
-(NSArray *)findData:(NSString *)bula
{
    
    NSString *sql = @"select * from LvYou;";
    if ([bula length] == 0) {
        sql = @"select * from LvYou;";
    }else{
        sql = @"select * from LvYou where image_id = ?";
    }
    //FMResult 这个类事涌来存放查找结果的 ，但是每次只能存放一个  要建一个可变数据来接受
    NSMutableArray * arr = [[NSMutableArray alloc]initWithCapacity:0];
    
    FMResultSet * set= [_dataBase executeQuery:sql ,bula];
    //协议个循环  用来查找数据库中的数据
    while ([set next]) {
        KouDaiDetailModel * model = [[KouDaiDetailModel alloc]init];
        model.id = [set stringForColumn:@"image_id"];
        model.image_url = [set stringForColumn:@"image_url"];
        model.name_zh_cn = [set stringForColumn:@"name"];
        model.name_en = [set stringForColumn:@"nameen"];
        [arr addObject:model];
    }
    
    return (NSArray *)arr;
    
}



@end
